package com.wss.common.utils;

import ohos.app.Context;
import ohos.net.NetCapabilities;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import org.jetbrains.annotations.NotNull;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Describe：网络状态工具类
 * Created by 吴天强 on 2018/10/25.
 */
public class NetworkUtil {

    /**
     * 是否有可用网络
     *
     * @param context context
     * @return boolean
     */
    public static boolean isNetworkEnabled(@NotNull Context context) {

        NetManager netManager = NetManager.getInstance(context);
        NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
        // NetCapabilities.NET_CAPABILITY_VALIDATED表示连接了网络，并且可以上网
        return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED);
    }

    /**
     * gps能用
     *
     * @param context ctx
     * @return boolean
     */
    public static boolean isGpsEnabled(@NotNull Context context) {
        //TODO 判断gps是否可用
        return false;
    }

    /**
     * Wifi是否可用
     *
     * @param context context
     * @return boolean
     */
    public static boolean isWifiEnabled(@NotNull Context context) {
        //TODO 判断Wifi是否可用
        return false;
    }

    /**
     * 当前网络是否为Wifi
     *
     * @param context context
     * @return boolean
     */
    public static boolean isWifi(@NotNull Context context) {
        //TODO 判断当前网络是否为Wifi
        return false;
    }


    /**
     * 当前网络是否为移动数据
     *
     * @param context context
     * @return boolean
     */
    public static boolean isMobile(@NotNull Context context) {
        //TODO 当前网络是否为移动数据
        return false;
    }

    /**
     * 获取当前网络IP
     *
     * @return 网络IP
     */
    public static String getIpAddress() {
        try {
            for (Enumeration<NetworkInterface> enNetI = NetworkInterface.getNetworkInterfaces(); enNetI
                    .hasMoreElements(); ) {
                NetworkInterface netI = enNetI.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = netI.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 检查是否为连接
     *
     * @param url url
     * @return boolean
     */
    public static boolean isLink(String url) {
        return ValidUtils.isValid(url) && (url.startsWith("http") || url.startsWith("https"));
    }
}
